from django import forms
from yyxt.utils.forms import FormMixin
from user.models import User


class RegisterForm(forms.ModelForm, FormMixin):
    """
    max_length,min_length,默认required=true,error_messages
    自定义验证 def clean_fields return fields
               def clean ; have no return
    form = LoginForm(json.loads(request.body))  # 提取非表单数据
    print(form)
    # LoginForm()传入{'username': 'user3', 'password': '000000'}即可
    if form.is_valid():
    """

    class Meta:
        model = User
        fields = ['user_name', 'job_num', 'tel', 'real_name', 'dep', 'group']
        error_messages = {
            'user_name': {
                'max_length': '用户名(8字符以内)->超出字数范围！',
                'unique': '用户名已存在！',
                'required': '用户名未填写！'
            },
            'job_num': {
                'unique': '工号已存在！',
                'required': '工号未填写！'
            },
            'tel': {
                'max_length': '请输入11位正确电话号码！',
                'min_length': '请输入11位正确电话号码！',
                'required': '电话号码未填写！'
            },
            'real_name': {
                'max_length': '真实姓名(8字符以内)->超出字数范围！',
                'required': '真实姓名未填写！'
            },
            'dep': {
                'max_length': '所属部门(64字符以内)->超出字数范围！',
                'required': '部位未填写！'
            },
        }
    #
    # def __init__(self, *args, **kwargs):
    #     super(RegisterForm, self).__init__(*args, **kwargs)
    #     self.fields['job_num'].required = False


class ChangeUserForm(forms.ModelForm, FormMixin):
    """用户修改表单"""

    class Meta:
        model = User
        fields = ['group']


class ChangePasswordForm(forms.Form, FormMixin):
    """修改密码验证"""
    password_repeat = forms.CharField()
    password = forms.CharField(
        max_length=10,
        min_length=6,
        error_messages={
            'max_length': '请输入6-10位密码！',
            'min_length': '请输入6-10位密码！',
            'required': '密码未填写！'
        }
    )

    def clean(self):
        """
        自定义验证两次密码是否一致
        :return: super().clean
        """
        cleaned_data = super().clean()
        password1 = cleaned_data.get('password')
        password2 = cleaned_data.get('password_repeat')
        if password1 != password2:
            raise forms.ValidationError('两次密码输入不一致！')
        else:
            return cleaned_data
